package com.wantup.demo03xd;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/3 13:32
 * <p>
 * 锁降级
 * 由读锁变成写锁
 */
public class LockDegradeDemo {

    private int num = 0;
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    private Lock readLock = lock.readLock();
    private Lock writeLock = lock.writeLock();


    public void dosomething() {
        writeLock.lock();
        try {
            num++;
            Thread.sleep(500);

            //在写锁还没有释放前就要获取 读锁 实现 所降级
            readLock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }


        try {
            if (num == 1) {
                System.out.println(" num 的值为 1");
            } else {
                System.out.println(" num 的值为 --> " + num);
            }
        } finally {
            readLock.unlock();
        }


    }


    public static void main(String[] args) {
        LockDegradeDemo degradeDemo = new LockDegradeDemo();
        for (int i = 0; i < 4; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    degradeDemo.dosomething();
                }
            }).start();
        }


    }

}
